package com.safewind.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.safewind.dao.AddressDao;
import com.safewind.model.Address;
import com.safewind.model.AddressData;
import com.safewind.model.AddressGroup;
import com.safewind.service.IAddressGroupService;
import com.safewind.service.IAddressService;
import com.safewind.util.ConstantUtil;
import com.safewind.util.ExcelUtil;
import com.safewind.util.StringUtil;

@Service("addressService")
public class AddressServiceImpl implements IAddressService {
	@Resource
	private AddressDao addressDao;

	@Resource
	private IAddressGroupService addressGroupService;

	@Override
	public Address getAddressById(String addressId) {
		return addressDao.selectByPrimaryKey(addressId);
	}

	@Override
	public void addAddress(Address address) {
		addressDao.insert(address);
	}

	@Override
	public void addAllAddress(List<Address> addrList) {
		for (Address addr : addrList) {
			this.addAddress(addr);
		}
	}

	@Override
	public List<AddressData> saveAddressByExport(File file, String userId)
			throws IOException, NumberFormatException {
		String[] heads = ExcelUtil.readExcelHead(file);
		List<List<Object>> dataList = ExcelUtil.readExcel(file);
		dataList.remove(0);
		Map<String, String> groupMap = resolveGroup(heads, dataList, userId);
		List<Address> addrList = new ArrayList<Address>();
		List<AddressData> list = new ArrayList<AddressData>();
		for (List<Object> objList : dataList) {
			Address add = resolveOneRow(heads, objList, groupMap);
			addrList.add(add);
			list.add(new AddressData(add, StringUtil.getKeyByValue(
					add.getGroupId(), groupMap)));
		}
		this.addAllAddress(addrList);
		return list;
	}

	private Map<String, String> resolveGroup(String[] heads,
			List<List<Object>> dataList, String userId) {
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < heads.length; i++) {
			if (heads[i].equals(ConstantUtil.GROUP)) {
				for (List<Object> objList : dataList) {
					if (objList.get(i).toString().equals("")) {
						map.put(ConstantUtil.DEFAULT, "1");
					} else {
						map.put(objList.get(i).toString(), "1");
					}
				}
				for (String key : map.keySet()) {
					AddressGroup ag = addressGroupService
							.selectAddressGroupByName(key, userId);
					if (ag != null && StringUtil.isNotBlank(ag.getPkId())) {
						map.put(key, ag.getPkId());
					} else {
						map.put(key, StringUtil.getUUID());
					}
				}
				addressGroupService.addGroupWithIdAndName(map, userId);
				return map;
			}
		}
		AddressGroup group = addressGroupService.getAddressGroupDefault(userId);
		map.put(ConstantUtil.DEFAULT, group.getPkId());
		return map;
	}

	private Address resolveOneRow(String[] heads, List<Object> objList,
			Map<String, String> groupMap) throws NumberFormatException {
		Address addr = new Address();
		for (int i = 0; i < heads.length; i++) {
			if (heads[i].equals(ConstantUtil.NAME)) {
				addr.setName(objList.get(i).toString());
				continue;
			}
			if (heads[i].equals(ConstantUtil.PHONE_NUMBER)) {
				if (StringUtil.isMobileNO(objList.get(i).toString())) {
					addr.setPhoneNumber(objList.get(i).toString());
				} else {
					throw new NumberFormatException();
				}
				continue;
			}
			if (heads[i].equals(ConstantUtil.GROUP)) {
				addr.setGroupId(groupMap.get(objList.get(i).toString()));
				continue;
			}
			if (heads[i].equals(ConstantUtil.REMARK)) {
				addr.setRemark(objList.get(i).toString());
				continue;
			}
		}
		if (StringUtil.isBlank(addr.getGroupId())) {
			addr.setGroupId(groupMap.get(ConstantUtil.DEFAULT));
		}
		addr.setAddTime(new Date());
		addr.setUpdateTime(new Date());
		addr.setPkId(StringUtil.getUUID());
		return addr;
	}

	@Override
	public void updateAddress(Address address) {
		addressDao.updateByPrimaryKeySelective(address);
	}

	@Override
	public void deleteAddressByIds(String ids) {
		if (StringUtil.isBlank(ids)) {
			return;
		}
		String[] id = ids.split(",");
		for (String str : id) {
			addressDao.deleteByPrimaryKey(str);
		}
	}

	@Override
	public void deleteAllByGroupId(String groupId) {
		addressDao.deleteAllByGroupId(groupId);
	}

	@Override
	public List<Address> getAllByGroupId(String groupId) {
		return addressDao.getAllByGroupId(groupId);
	}

	@Override
	public Address selectAddressByPhoneNumberAndGroup(String PhoneNumber,
			String groupId) {
		List<Address> list = addressDao.selestAddressByPhoneNumberAndGroup(
				PhoneNumber, groupId);
		if (list != null && list.size() != 0) {
			return list.get(0);
		}
		return new Address();
	}

	@Override
	public void updateGroupIds(String ids, String groupId) {
		if (StringUtil.isBlank(ids)) {
			return;
		}
		String str[] = ids.split(",");
		for (String id : str) {
			Address address = new Address();
			address.setGroupId(groupId);
			address.setPkId(id);
			address.setUpdateTime(new Date());
			this.updateAddress(address);
		}

	}

	@Override
	public List<Address> getAddressListByIds(List<String> param) {
		return addressDao.getAddressListByIds(param);
	}

}
